/**
 * New node file
 */

var fs = require('fs');

module.exports = {
	
	index : function(req, res){
		return res.view('mobile/index', {'login':true});
	},
	
	adminIndex : function(req, res){
		return res.view('index');
	},
	
	doLogin : function(req, res){
		
		var userid = req.param("userid");
		var passwd = req.param("passwd");
		
		var isAdmin = (sails.config.application.root.userid == userid && sails.config.application.root.passwd == passwd);
		
		if(isAdmin){
			req.session.user = {
				'userid' : userid
			};
			return res.redirect(sails.config.application.adminPath);
		}else{
			return res.redirect(sails.config.application.adminPath + '/login');
		}
		
	},

	doWxlogin : function(req, res){
		var code = req.param("code");
		WechatService.getUserByCode(code, function(err, result){
			if(!err){
				req.session.user = result;
				sails.log.info('user [' + result.userid + '] login.');
				return res.redirect(sails.config.application.appPath);
			}else{
				return res.serverError(err, '403');
			}
		});
	},
	
	logout : function(req, res){
		req.session.user = null;
		
		var reqPath = req.path;
		if (reqPath.startWith(sails.config.application.appPrefix)) {
			return res.redirect(sails.config.application.appPath);
		}else{
			return res.redirect(sails.config.application.adminPath);
		}
	},

	install : function(req, res){
		
		var leaveNoteType = sails.config.application.sysform.note;
		var vacationType = sails.config.application.vacationType;
		
		var formTypes = [
			{id:leaveNoteType, 'name':'请假条', seq : 1, system:true},
			{id:50, 'name':'通用报表1', seq : 2, system:false},
			{id:51, 'name':'通用报表2', seq : 3, system:false}
		];
		
		var leaveTypes = [
			{id:vacationType, 'name':'年假', seq : 1},
			{id:11, 'name':'事假', seq : 2},
			{id:12, 'name':'病假', seq : 3}
		];
		
		var formProps = [
			{'name':'属性1', seq : 1, formType : 50},
			{'name':'属性2', seq : 2, formType : 50, validator : "{required:true,email:true}"},
			{'name':'属性3', seq : 3, formType : 50},
			{'name':'属性4', seq : 1, formType : 51},
			{'name':'属性5', seq : 2, formType : 51},
			{'name':'属性6', seq : 3, formType : 51}
		]
		
		FormType.create(formTypes).then(function createCB(created){
			
			LeaveType.create(leaveTypes).then(function createCB(created){
				
				FormProp.create(formProps).then(function createCB(created){
					
					return res.redirect(sails.config.application.adminPath);
					
				});
				
			});
			
		});
		
	},
	
	files : function(req, res){
		
		var filename = req.param("filename");
		var file = sails.config.appPath + sails.config.application.uploadPath + '/' +  filename + '.jpg';
		
		fs.readFile(file, function(err, data) {
			if (err){
				sails.log.error(err);
				return res.serverError(err);
			}else{
				res.writeHead(200, {'Content-Type': 'image/jpeg'});
				res.end(data);
			}
		});
		
	}

}
